﻿
; (function ($, window, document, undefined) {

    var pluginName = "grid", defaults = { id: '', key: '', title: {}, cols: [], toolbar: {}, rowindex: true, data: [], pageindex: 0, pagesize: 10, pager: null, rowbind: null };

    function Plugin(element, options) {
        this.element = $(element);
        this.settings = $.extend({}, defaults, options);
        this._defaults = defaults;
        this._name = pluginName;
        this.init();
    }

    Plugin.prototype = {
        init: function () {

            var $this = this.element,
                $toggle = this.settings.toggle,
                obj = this;

            if (this.isIE() <= 9) {
                return false;
            }

            if (this.settings.id == '') {
                return false;
            }

            this.bind();
        },

        bind: function () {
            //alert(this.settings.id);
            var rowindex = this.settings.rowindex;
            var checkbox = this.settings.checkbox;
            var pager = this.settings.pager;
            var rowbind = this.settings.rowbind;
            var cols = this.settings.cols;
            var data = this.settings.data;
            var gridid = this.settings.id;
            var keys = [];
            var thead = checkbox ? '<th style="text-align:center; width:40px;"><input type="checkbox" name="' + gridid + '" /></th>' : '';
            thead += rowindex ? '<th style="text-align:center;">#</th>' : '';
            $(cols).each(function (i, col) {
                thead += '<th>' + col.label + '</th>';
                if ($.inArray(col.key, keys) < 0)
                    keys.push(col.key);
            });
            var tbody = '';
            $(data).each(function (i, m) {
                
                tbody += '<tr>';
                tbody += checkbox ? '<td style="text-align:center;"><input type="checkbox" name="' + gridid + '" /></td>' : '';
                tbody += rowindex ? '<td style="text-align:center;">' + (i + 1) + '</td>' : '';

                if (rowbind) {
                    rowbind(i, m);
                }

                $(keys).each(function (j, key) {
                    tbody += '<td>' + m[key] + '</td>';
                });
                tbody += '</tr>';
            });

            if (tbody != '' && pager && this.settings.pageindex && this.settings.pagesize && this.settings.total) {
                var p = this.pager();
                if (p != '')
                    tbody += '<tr><td colspan="' + (cols.length + 1) + '">' + p + '</td></tr>';
            }

            if (tbody == '')
                tbody = '<tr><td colspan="' + (cols.length + 1) + '"><div class="alert alert-danger" role="alert">No Records !</div></td></tr>';

            var table = '<table class="table table-striped table-bordered table-hover"><thead><tr class="active">' + thead + '</tr></thead><tbody>' + tbody + '</tbody></table>';
            this.element.html(table);

            if (pager && this.settings.pageindex && this.settings.pagesize && this.settings.total) {
                var g = this;
                this.element.find('nav').click(function (e) {
                    e = e || window.event;
                    var target = e.target || e.srcElement;
                    if (target.nodeName.toString() == "A") {
                        var text = $.trim($(target).text());
                        var pageindex = 1

                        if (text == 'Previous' && g.settings.pageindex == 1)
                            return false;
                        else if (text == 'Previous')
                            pageindex = g.settings.pageindex - 1;
                        else if (text == 'Next' && g.settings.pageindex * g.settings.pagesize >= g.settings.total)
                            return false;
                        else if (text == 'Next')
                            pageindex = g.settings.pageindex + 1;
                        else
                            pageindex = parseInt(text);
                        if (isNaN(pageindex))
                            return false;
                        g.settings.pageindex = pageindex
                        pager(g.settings, function (setting) {
                            g.settings = setting;
                            g.bind();
                        });
                    }
                });
            }
        },

        pager: function () {
            var pageindex = this.settings.pageindex;
            var pagesize = this.settings.pagesize;
            var total = this.settings.total;
            var nav = '<nav><ul class="pagination">';

            var pagernum = parseInt(total / pagesize) + (total % pagesize > 0 ? 1 : 0);
            //return 'pagernum=' + pagernum;

            if (pagernum <= 1)
                return '';

            if (pagernum <= 5) {
                for (var i = 1; i <= pagernum ; i++) {
                    if (pageindex == i)
                        nav += '<li class="active"><a href="#">' + i + '</a></li>';
                    else
                        nav += '<li><a href="#">' + i + '</a></li>';
                }
                nav += '</ul></nav>';
                return nav;
            }

            nav += '<li' + ((pageindex == 1) ? ' class="disabled"' : '') + '><a href="#" aria-label="Previous">Previous</a></li>';

            var s = pageindex - 2; 
            s = s <= 0 ? 1 : (pagernum - s < 5 ? pagernum - 4 : s);

            var e = pageindex + 2;
            var e = (e > pagernum) ? pagernum : (e - 5 <= 0 ? 5 : e);


            for (var i = s; i <= e; i++) {
                if (pageindex == i)
                    nav += '<li class="active"><a href="#">' + i + '</a></li>';
                else
                    nav += '<li><a href="#">' + i + '</a></li>';
            }

            nav += '<li' + ((pageindex == pagernum) ? ' class="disabled"' : '') + '><a href="#" aria-label="Next">Next</a></li>';

            nav += '</ul></nav>';
            return nav;


        },

        gridClick: function () {
            var thisobj = this, checkbox = this.settings.checkbox, gridid = this.settings.id;
            $(gridid).click(function (e) {
                e = e || window.event;
                var target = e.target || e.srcElement;
                if (target.nodeName.toString() == "INPUT") {
                    if (checkbox && $(target).attr('type') == 'checkbox' && $(target).attr('name') == gridid) {
                        thisobj.check($(target), gridid);
                    }
                }
            });
        },
        check: function ($chk, gridid) {
            var selectchkitems = gridid + ' td input[name="' + gridid + '"]', selectchkall = gridid + ' th input[name="' + gridid + '"]';

            if ($chk.parent()[0].nodeName == 'TH') {
                var checked = $chk[0].checked;
                $(selectchkitems).each(function () {
                    $(this)[0].checked = checked;
                });
            } else {
                var chked = true;
                $(selectchkitems).each(function () {
                    chked = chked && $(this)[0].checked;
                });
                $(selectchkall)[0].checked = chked;
            }


            console.log('00...00  ' + '  len=' + $(selectchkitems).length);
        },

        isIE: function () { //https://gist.github.com/padolsey/527683
            var undef,
                v = 3,
                div = document.createElement("div"),
                all = div.getElementsByTagName("i");

            while (
                div.innerHTML = "<!--[if gt IE " + (++v) + "]><i></i><![endif]-->",
                all[0]
            ) {
                return v > 4 ? v : undef;
            }
        },

        remove: function () {
            this.element.off("." + pluginName);
            this.element.removeData(pluginName);
        }

    };


    $.fn[pluginName] = function (options) {
        this.each(function () {
            var el = $(this);
            if (el.data(pluginName)) {
                el.data(pluginName).remove();
                el.data(pluginName, new Plugin(this, options));
            } else {
                el.data(pluginName, new Plugin(this, options));
                el.data(pluginName).gridClick();
            }
        });
        return this;
    };

})(jQuery, window, document);